# -*- coding: utf-8 -*-

begin
  require 'rubygems'
rescue LoadError
  #
end
require "sqlite3"

class DBConnect
  
  def initialize(host, user, pass, database)
  
    open(host, user, pass, database)
  
  end
  
  def open(host, user, pass, database)
    
    @db = SQLite3::Database.new($class_dir + "db/#{database}.db")
    
  end
  
  def close()
    
    @db.close()
    
  end
  
  def query(sql)
    
    #print "#{sql}<br />"
    return sql2array(sql)
    
  end
  
  def exec(sql)
    
    output_log($logfile, "[#{Time.now}] #{sql}\n")
    @db.execute(sql)
    
  end
  
  def sql2array(sql)
    
    rs = @db.execute2(sql)
    
    i = 0
    flg = true
    fields = []
    values = []
    
    rs.each do |row|
      
      if flg then
        fields = row
        flg = false
      else
        
        j = 0
        val = {}
        row.each do |wk|
          val[fields[j]] = wk
          j += 1
        end
        values[i] = val
        i += 1
        
      end
      
    end
    
    return values
    
  end
  
  def list_fields(table)
    
    fields, *rows = @db.execute2("select * from `#{table}`")
    return fields
    
  end
  
  def escape_string(str)
    #val = @db.escape_string(str.to_s)
    str = str.gsub("'", "''")
    return str
  end
  
end
